package com.hankol.winecellar.fragment

import androidx.lifecycle.Observer
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseLazyFragment
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.toast
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.ARouterUtils
import com.baselibrary.utils.DoubleClickHelper
import com.baselibrary.utils.SpUtils
import com.hankol.winecellar.R
import com.hankol.winecellar.adapter.GoodsOrderListAdapter
import com.hankol.winecellar.bean.GoodsOrderListBean
import com.hankol.winecellar.databinding.FragmentGoodsOrderBinding
import com.baselibrary.utils.EmptyViewUtil
import com.hankol.winecellar.utils.PopUtils
import com.hankol.winecellar.viewmodel.WineCellarViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**经营者-销售订单列表
 * 待付款、待发货、待收货、已完成、全部
 * @author: merbng
 * @time: 2022/9/6 11:55
 * @description:
 */
class GoodsOrderFragment(var status: Int = -1,val dealerCode:String="") : BaseLazyFragment(false) {
    private lateinit var binding: FragmentGoodsOrderBinding
    private lateinit var viewModel: WineCellarViewModel
    private val mAdapter: GoodsOrderListAdapter by lazy { GoodsOrderListAdapter() }
    var page = 1
    private var hasnext: Boolean = false
    private var clickOrderBean: GoodsOrderListBean? = null
    private var clickOrderPos = -1
    private var keyword = ""

    companion object {
        //状态:-1-全部，0-待付款，1-待发货，2-待收货,5-已完成
        fun newInstance(status: Int = -1,dealerCode:String=""): GoodsOrderFragment {
            return GoodsOrderFragment(status,dealerCode)
        }
    }

    fun setKeyWord(keyword: String) {
        this.keyword = keyword
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_goods_order
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        viewModel = getFragmentViewModelProvider(this).get(WineCellarViewModel::class.java)
        binding = getDataBinding<FragmentGoodsOrderBinding>()
        initView()
        initListener()
        initObserver()
    }


    private fun initObserver() {
        viewModel.orderDataLD.observe(requireActivity(), Observer {
            binding.smartOrder.finishRefresh()
            binding.smartOrder.finishLoadMore()
            if (it == null || it.data.isNullOrEmpty()) {
                //无数据
                if (page == 1) {
                    mAdapter.setNewData(it.data)
                }
                mAdapter.emptyView = EmptyViewUtil.getEmptyView(Constants.TYPE_ORDER_LIST, binding.rvOrderList, "暂无订单")
            } else {
                if (it.data.checkNotNull()) {
                    hasnext = it.hasnext
                    if (page == 1) {
                        mAdapter.setNewData(it.data)
                    } else {
                        mAdapter.addData(it.data)
                    }
                    page++
                }
            }
        })
        viewModel.saveSendGoodsLD.observe(this, Observer {
            if (it.success) {
                "发货成功".toast()
                page = 1
                loadData()
            }
        })
        //填写发货信息
        viewModel.allComponyLD.observe(this, Observer {
            PopUtils.showSendGoodsDialog(requireActivity(), it, "","",false, object : PopUtils.ISendGoodsCallback {
                override fun onClickSendGoods(type: String, code: String) {
                    clickOrderBean?.let {
                        viewModel.reqSaveSendGoodsInfo(type, code, it.poId)
                    }
                }
            })
        })
    }

    private fun initView() {
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val orderBean = adapter.data[position] as GoodsOrderListBean
            //进入订单详情
            val hashMap = HashMap<String, Any>()
            hashMap[Constants.KEY_ORDER_ID] = orderBean.poId
            ARouterUtils.jump(ActivityRouter.WINE_CELLAR.ORDER_DETAIL, hashMap)
        }
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            clickOrderPos = position
            clickOrderBean = mAdapter.data[position]
            when (view.id) {
                R.id.rl_order_multiple, R.id.ll_price_num, R.id.rl_order_list_item -> {
                    if (!DoubleClickHelper.isOnDoubleClick()) {
                        //进入订单详情
                        val hashMap = HashMap<String, Any>()
                        hashMap[Constants.KEY_ORDER_ID] = "${clickOrderBean?.poId}"
                        ARouterUtils.jump(ActivityRouter.WINE_CELLAR.ORDER_DETAIL, hashMap)
                    }
                }
                R.id.tv_send_goods -> {
                    if (!DoubleClickHelper.isOnDoubleClick()) {
                        viewModel.reqGetAllCompony()
                    }
                }
            }
        }
        binding.rvOrderList.adapter = mAdapter
    }


    fun loadData(isReply: Boolean = false) {
        if (isReply) {
            page = 1
        }
        val tempDealerCode=if (dealerCode.checkNotNull())dealerCode else SpUtils.getInstance().currentWineryInfo.dealerCode
        viewModel.reqGoodsOrderList(tempDealerCode, status, keyword, page)
    }

    override fun lazyLoadData() {
        page = 1
        loadData()
    }

    fun initListener() {
        binding.smartOrder.setOnRefreshListener {
            page = 1
            loadData()
        }
        binding.smartOrder.setOnLoadMoreListener {
            if (hasnext) {
                loadData()
            } else {
                binding.smartOrder.finishLoadMore()
            }
        }
    }

    private fun setEmptyView() {
        if (mAdapter.data.isNullOrEmpty()) {
            mAdapter.emptyView = EmptyViewUtil.getEmptyView(Constants.TYPE_ORDER_LIST, binding.rvOrderList, "暂无订单")
        }
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        when (messageBus.codeType) {
            MessageBus.msgId_del_order -> {
                if (status == -1) {
                    val poid = messageBus.param1
                    //删除订单
                    for (i in mAdapter.data.indices) {
                        if ("${(mAdapter.data[i] as GoodsOrderListBean).poId}" == poid) {
                            mAdapter.data.removeAt(i)
                            mAdapter.notifyItemRemoved(i)
                            setEmptyView()
                        }
                    }
                }
            }
//            MessageBus.msgId_search_order -> {
//                //搜索订单
//                keyword = messageBus.param1.toString()
//                page = 1
//                loadData()
//            }
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }
}